package com.tony.akka.sample4;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;

/**
 * @version V1.0  </br>
 * @ClassName CompletionStageUtils </br>
 * @Description TODO  </br>
 * @Author tonywang</br>
 * @DATE 3/19/2019 2:50 PM</br>
 */
public class CompletionStageUtils {
    /**
     * Retry an operation returning a completion stage up to maxRetries times in case the
     * completion stage is failed.
     */
    public static <T> CompletionStage<T> withRetries(Supplier<CompletionStage<T>> tFactory, int maxRetries) {
        return tFactory.get().handle((t,  failure)-> {
            if (failure == null) {
                return CompletableFuture.completedFuture(t);
            } else if (maxRetries > 0) {
                return withRetries(tFactory, maxRetries - 1);
            } else {
                throw new RuntimeException("Reached max retries", failure);
            }
        }).thenCompose(stageT ->stageT);
    }
}
